package com.ebupt.migu.music.common.utils;

import com.ebupt.migu.music.userGroup.mapper.NewCrowdMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: liuyangyang@cd.ebupt.com
 * @create: 2020-11-10 10:44
 */
@Component
public class UpdateUserGroupSize {

    @Autowired
    private NewCrowdMapper newCrowdMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${message.send_url}")
    private String SEND_MESSAGE_URL;

    public static UpdateUserGroupSize updateUserGroupSize;

    @PostConstruct
    public void init() {
        updateUserGroupSize = this;
        updateUserGroupSize.newCrowdMapper = this.newCrowdMapper;
    }
    /**
     * 更新人群规模
     *
     * @param groupID
     * @param type    人群类型 1- 文件上传； 2- 非文件上传；
     */
    public void update(String groupID, int type, int size) {
        Map<String, Object> map = new HashMap<>();
        int user_group_size = 0;
        // uid 规模
        int client_user = 0;
        // 手机号码规模
        int mobile_user = 0;
        // 设备号规模
        int device_user = 0;
        // 备注
        String remark;
        // redis key
        String _phone = groupID + "-phone";
        String _imei = groupID + "-imei";
        String _uid = groupID + "-uid";
        if (redisTemplate.hasKey(_uid)) {
            client_user = redisTemplate.opsForSet().size(_uid).intValue();
        }
        if (redisTemplate.hasKey(_imei)) {
            device_user = redisTemplate.opsForSet().size(_imei).intValue();
        }
        if (redisTemplate.hasKey(_phone)) {
            mobile_user = redisTemplate.opsForSet().size(_phone).intValue();
        }
        map.put("ftpSize", size);
        user_group_size = CommonUtil.maxValue(client_user, mobile_user, device_user);
        map.put("clientUser", client_user);
        map.put("mobileUser", mobile_user);
        map.put("deviceUser", device_user);
        map.put("userGroupSize", user_group_size);
        if (user_group_size > 7000000) {
            map.put("remark", "人群规模超过700万");
            // 文件上传创建失败：提取失败
            // 给人群创建人和维护人发送消息
            HttpUtils.doPost(SEND_MESSAGE_URL,new SendMessageEntity("1","4",null,groupID));
            HttpUtils.doPost(SEND_MESSAGE_URL,new SendMessageEntity("2","4",null,groupID));
            if (type == 1) {
                map.put("createStatus", 7);
            } else {
                map.put("createStatus", 6);
            }
        } else {
            map.put("createStatus", 5);
        }
        map.put("groupId",groupID);
        this.newCrowdMapper.updateCrowd(map);
    }
}
